class DospyWaterTask < ActiveRecord::Base
  validates_presence_of :forum_code,
    :forum_url,
    :status
    
  def rewater!(options = {})
    self.status = 'waiting'
    self.trying_count = 0
    self.forum_url = options[:forum_url] if options[:forum_url].present?
    self.proxy_ip_and_port = options[:proxy_ip_and_port] if options[:proxy_ip_and_port].present?
    save(false)
  end
  
  def status
    ActiveSupport::StringInquirer.new(self[:status])
  end
  
  def watering!
    self.trying_count += 1
    self.status = 'watering'
    save(false)
  end
  
  def exception!(exception_message)
    self.status = 'exception'
    self.the_last_exception = exception_message
    save(false)
  end
  
  def success!
    self.status = 'success'
    save(false)
  end
  
  def try_water(time = 0)
    if time < 3
      begin
        logger.debug "================================="
        logger.debug " === #{forum_code} #{ "第#{time + 1}次尝试" if time > 0}"
        logger.debug "================================="
        watering!
        DospyWater.new(:forum_code => forum_code,
          :forum_uri => forum_url,
          :proxy_ip_and_port => proxy_ip_and_port
        ).watering
        success!
      rescue Exception => e
        logger.error "----------------------------------"
        logger.error " --- #{forum_code}发帖失败:#{e.to_s}"
        logger.error "----------------------------------"
        exception!(e.to_s)
        try_water(time + 1)
      end
    end
  end
  
  def self.watering!
    #all(:conditions => ['status = ? and trying_count < 3', 'waiting']).each_with_object([]) do|task, threads|
    #  threads << Thread.new(task) do |task|
    #    task.try_water
    #  end
    #end.each do |thread|
    #  thread.join
    #end
    all(:conditions => ['status = ? and trying_count < 3', 'waiting']).each do |task|
      task.try_water
    end
  end
end
